package com.kh.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kh.reggie.common.Result;
import com.kh.reggie.dto.EmailCodeDTO;
import com.kh.reggie.entity.User;
import com.kh.reggie.service.UserService;
import com.kh.reggie.utils.VerifyCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private VerifyCodeUtil verifyCodeUtil;
    /**
     * 发送验证码
     * @param user
     * @return
     */
    @PostMapping("sendMsg")
    public Result<String> sendEmail(@RequestBody User user, HttpSession session){
        String code = verifyCodeUtil.generateVerifyCode(6);
        log.info("手机号Phone:{}   验证码Code:{}",user.getPhone(),code);
        //把验证码存入Session，验证用，phone为Key，code为value
        session.setAttribute(user.getPhone(), code);
        return userService.sendEmail(user.getPhone(),code);
    }

    /**
     * 验证登入
     * @param emailCodeDTO
     * @return
     */
    @PostMapping("login")
    public Result<String> login(@RequestBody EmailCodeDTO emailCodeDTO,HttpSession codeInSession){
        log.info("登入账号为{}",emailCodeDTO.getPhone());
        //拿到验证码和手机号
        String code = emailCodeDTO.getCode();
        String phone = emailCodeDTO.getPhone();
        //从session中拿到对应的验证码
        String tempCode = (String) codeInSession.getAttribute(phone);
        try {
            //验证码相等
            if (code.equals(tempCode) && codeInSession != null) {
                //是否为新用户，如果是新用户顺手注册了
                LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(User::getPhone, phone);
                //只能用getOne来匹配，不能用getById，因为没有Id给你匹配，都是空的
                User user = userService.getOne(lambdaQueryWrapper);
                if (user==null){
                    //用户不存在，注册一下，注册完放行
                    //用户的ID是有自动生成策略的，不用管
                    user = new User();
                    user.setPhone(phone);
                    user.setStatus(1);
                    userService.save(user);
                }
                //把用户的ID存入Session，留给过滤器进行验证放行
                codeInSession.setAttribute("user", user.getId());
                codeInSession.setAttribute(phone,"");
                return Result.success("登陆成功，欢迎~");
            }
        }catch (Exception e) {
            return Result.error("系统错误");
        }

        return Result.error("验证码错误");
    }
}
